package com.bos.web.action;
import com.bos.domian.constant.Constants;
import com.bos.utils.MailUtils;
import com.bos.utils.PhoneFormatCheckUtils;
import com.bos.web.BaseAction;
import com.crm.domain.Customer;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author misterWei
 * @create 2018年11月18号:00点19分
 * @mailbox mynameisweiyan@gmail.com
 */
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
    //验证码获取信息
    private String authcode;
    //Redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    public void setAuthcode(String authcode) {
        this.authcode = authcode;
    }

    @Action(value = "verifyPhone",results ={@Result(type = "json")})
    public String verifyPhone(){
        try {
            String randomCode = RandomStringUtils.randomNumeric(4);
            //校验手机号码操作
            if (! PhoneFormatCheckUtils.isPhoneLegal(model.getTelephone())) {
                ActionContext.getContext().getValueStack().push("phoneFormat");

                return SUCCESS;
            }
            System.out.println(randomCode);
            //发送手机号码操作 使用短信MQ平台进行发送
            jmsTemplate.send("bos_sms_queue", new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    MapMessage mapMessage = session.createMapMessage();
                    mapMessage.setObject("telephone",model.getTelephone());
                    mapMessage.setObject("content",randomCode);
                    return mapMessage;
                }
            });
           // SendMessageUtil.sendSmsByHTTP(model.getTelephone(),randomCode);
           //验证码存入session中
          ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),randomCode);
            ActionContext.getContext().getValueStack().push("OK");

            return SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            ActionContext.getContext().getValueStack().push("error");

            return SUCCESS;

        }
    }
    @Action(value = "register",results = {@Result(location = "/signup-success.html"),@Result(name = "input",location = "/signup.html")})
    public String register(){
        String checkPhone = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());

            //两次验证码不一样直接返回重新注册页面
          if ( ! authcode.equals(checkPhone)) {
                  return INPUT;
        }else {
            //1 调用 webService远程服务来保存数据信息
            WebClient.create(Constants.CRM_MANAGERMENT+"/services/customerService/saveCustomer").encoding("utf-8").accept(MediaType.APPLICATION_JSON).post(model);
            //2 发送邮箱确定绑定邮箱
              //标题
              String subject="BOS系统AUTO";
             //发送的邮箱
              String to = model.getEmail();
              //验证码
              String activecode =  RandomStringUtils.randomNumeric(16);
              //手机号
              String phoneNumber = model.getTelephone();
              //需要使用Redis进行存储以手机号为key  随机码为value  定时24小时
              redisTemplate.opsForValue().set(phoneNumber,activecode,24, TimeUnit.HOURS);
              MailUtils.sendMail(subject,to,activecode,phoneNumber);
            //注册成功
            return SUCCESS;
        }
    }
    //验证码
    private String activecode;

    public void setActivecode(String activecode) {
        this.activecode = activecode;
    }

    @Action(value = "auto_email")
    public void autoEmail() throws IOException {
        //设置编码
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        //拿出存储的验证码信息
        String autoCode = redisTemplate.opsForValue().get(model.getTelephone());
        //验证 如果 验证码不存在,或者是null
        if (activecode == null || ! autoCode.equals(activecode)) {
            response.getWriter().println("<h1><font color='red'>邮箱验证码不存在!</font></h1>");
        }else {
            //如果核实清楚后   调用远程服务信息
            //查询邮箱是否绑定
            Customer customer = WebClient.create(Constants.CRM_MANAGERMENT+"/services/customerService/findTelephone/" + model.getTelephone()).encoding("utf-8").accept(MediaType.APPLICATION_JSON).get(Customer.class);
            System.err.println(customer);
            if (customer != null) {
                if (customer.getType() != null) {

                    //绑定过了
                    response.getWriter().println("<h1><font color='red'>已经绑定过了哦!</font></h1>");

                }else {
                    //没有绑定就绑定
                    WebClient.create(Constants.CRM_MANAGERMENT+"/services/customerService/updateEmailStatus/" + model.getTelephone()).encoding("utf-8").get();
                    response.getWriter().println("<h1><font color='red'>绑定成功!</font></h1>");
                }

            }else {
                response.getWriter().println("<h1><font color='red'>请联系管理员 严重错误报告!</font></h1>");
            }
            //清除Redis邮箱验证码信息
            redisTemplate.delete(model.getTelephone());
        }
    }
     //提交的验证码信息
    private String securityCode;

    public void setSecurityCode(String securityCode) {
        this.securityCode = securityCode;
    }

    @Action(value = "customer_login",results = {@Result(name = "success", type = "redirect",location = "/index.html#/myhome"),@Result(name = "login",type = "redirect",location = "/login.html")})
    public String customerLogin(){
        String code = (String) ServletActionContext.getRequest().getSession().getAttribute("code");
        if (code == null) {  //如果验证码为null
            return  LOGIN;
        }else if (! code.equalsIgnoreCase(securityCode)){  //如果提交的验证码和session的验证码不一致
            return  LOGIN;
        }
        //验证信息
        Customer customer = WebClient.create(Constants.CRM_MANAGERMENT+"/services/customerService/login/"+model.getTelephone()+"/"+model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
        if (customer!=null) {
            ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
            return SUCCESS;
        }else {
            return  LOGIN;
        }


    }

}
